package guda.mrpc.core.client;


import guda.mrpc.core.RpcResponse;
import guda.mrpc.core.api.Request;
import guda.mrpc.core.api.Response;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class RpcFuture {

    private Request request;
    private Response response;
    private Lock lock = new ReentrantLock();
    private Condition finish = lock.newCondition();

    public RpcFuture(Request request) {
        this.request = request;
    }

    public Object get() throws Exception {
        return get(request.getTimeout());
    }

    public Object get(int seconds) throws Exception {
        try {
            lock.lock();
            finish.await(seconds, TimeUnit.SECONDS);
            if (null != response) {
                return response.getResult();
            }
            return null;
        } finally {
            lock.unlock();
        }
    }

    public void done(RpcResponse reponse) {
        try {
            lock.lock();
            this.response = reponse;
            finish.signal();

        } finally {
            lock.unlock();
        }
    }

}